using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Raptor.Client
{
  public partial class frmEmbededObjects : Form
  {
    private bool bDisableUnselect = false;
    /// <summary>
    /// Comment
    /// </summary>
    public List<String> ListObjectProperties = new List<String>();

    public List<List<String>> ListObjects = new List<List<string>>();

    private frmMain m_ReturnForm;

    private List<List<String>> m_SelectedList;

    public frmMain returnForm
    {
      get { return m_ReturnForm; }
      set { m_ReturnForm = value; }
    }

    private string m_TableName;

    public string TableName
    {
      get { return m_TableName; }
      set { m_TableName = value; }
    }

    public List<List<String>> SelectedList
    {
      get { return m_SelectedList; }
      set { m_SelectedList = value; }
    }

    private SqlConnection m_ActiveConn;

    public SqlConnection ActiveConn
    {
      get { return m_ActiveConn; }
      set { m_ActiveConn = value; }
    }

    public frmEmbededObjects()
    {
      InitializeComponent();
    }

    private void frmEmbededObjects_Load(object sender, EventArgs e)
    {
      DataSet DSObjects = new DataSet();
      DataSet DSLists = new DataSet();

      int iRowIndex = 0;
      int iSelectedListCount = 0;
      int iSelectedObjectCount = 0;
      //For all reference From this table
      string sSQLObjectsString =  "Select 'Constraint' = sys.foreign_keys.name," +
                              "'Table' = sys.objects.name, " +
                              "'Column' = col_name(sys.objects.object_id, sys.foreign_key_columns.parent_column_id)," +
                              "'ReferencedTable' = referencedobject.name," +
                              "'ReferencedColumn' = col_name(referencedobject.object_id, sys.foreign_key_columns.referenced_column_id)" +
                              "From sys.foreign_keys" +
                              " inner join sys.objects on sys.objects.object_id = sys.foreign_keys.parent_object_id" +
                              " inner join sys.objects referencedobject on referencedobject.object_id = sys.foreign_keys.referenced_object_id" +
                              " inner join sys.foreign_key_columns on sys.foreign_key_columns.constraint_object_id = sys.foreign_keys.object_id" +
                              " where sys.foreign_keys.type = 'f'" +
                              "  and sys.objects.name like '" + this.m_TableName + "'";

      //For all reference To this table (Dependant Tables)
      string sSQLListsString = "Select 'Constraint' = sys.foreign_keys.name," +
                            "'Table' = sys.objects.name," +
                            "'Column' = col_name(sys.objects.object_id, sys.foreign_key_columns.referenced_column_id)," +
                            "'ReferencedTable' = referencedobject.name," +
                            "'ReferencedColumn' = col_name(referencedobject.object_id, sys.foreign_key_columns.parent_column_id)" +
                            " From sys.foreign_keys" +
                            " inner join sys.objects on sys.objects.object_id = sys.foreign_keys.referenced_object_id" +
                            " inner join sys.objects referencedobject on referencedobject.object_id = sys.foreign_keys.parent_object_id" +
                            " inner join sys.foreign_key_columns on sys.foreign_key_columns.constraint_object_id = sys.foreign_keys.object_id" +
                            " where sys.foreign_keys.type = 'f'" +
                            " and sys.objects.name like '" + this.m_TableName + "'";

      SqlDataAdapter SQAObjects = new SqlDataAdapter(sSQLObjectsString, ActiveConn);
      SqlDataAdapter SQALists = new SqlDataAdapter(sSQLListsString, ActiveConn);

      try
      {
        SQAObjects.Fill(DSObjects);
        SQALists.Fill(DSLists);

        if (DSObjects.Tables[0].Rows.Count > 0 || DSLists.Tables[0].Rows.Count > 0)
        {
          chkListAll.Enabled = true;
          chkObjectAll.Enabled = true;
          btnSave.Enabled = true;
        }
        else
        {
          chkObjectAll.Enabled = false;
          chkListAll.Enabled = false;
          btnSave.Enabled = false;
        }

        foreach (DataRow dr in DSObjects.Tables[0].Rows)
        {
          ListObjectProperties = new List<string>();
          iRowIndex = GrdForeignKeys.Rows.Add(false, dr["Constraint"].ToString(), dr["Table"].ToString(), dr["Column"].ToString(), dr["ReferencedTable"].ToString(), dr["ReferencedColumn"].ToString(), false,false,false);
          ListObjectProperties.Add(dr["Table"].ToString());
          ListObjectProperties.Add(dr["Column"].ToString());
          ListObjectProperties.Add(dr["ReferencedTable"].ToString());
          ListObjectProperties.Add(dr["ReferencedColumn"].ToString());
          ListObjects.Add(ListObjectProperties);
          if (SelectedList != null && SelectedList.Count > 0)
          {
            for (int i = 0; i < SelectedList.Count; i++)
            {
              if (SelectedList[i][2] == dr["ReferencedTable"].ToString())
              {
                (GrdForeignKeys.Rows[iRowIndex].Cells[0] as DataGridViewCheckBoxCell).Value = bool.Parse(SelectedList[i][4]);
                if (bool.Parse(SelectedList[i][4]))
                  iSelectedObjectCount++;

                if (bool.Parse(SelectedList[i][6]))
                  (GrdForeignKeys.Rows[iRowIndex].Cells[7] as DataGridViewCheckBoxCell).Value = true;
                else
                  (GrdForeignKeys.Rows[iRowIndex].Cells[7] as DataGridViewCheckBoxCell).Value = false;

                //if (bool.Parse(SelectedList[i][7]))
                //  (GrdForeignKeys.Rows[iRowIndex].Cells[8] as DataGridViewCheckBoxCell).Value = true;
                //else
                //  (GrdForeignKeys.Rows[iRowIndex].Cells[8] as DataGridViewCheckBoxCell).Value = false;
              }
            }
          }
        }
        foreach (DataRow dr in DSLists.Tables[0].Rows)
        {
          ListObjectProperties = new List<string>();
          iRowIndex = GrdRelationships.Rows.Add(false,dr["Constraint"].ToString(), dr["Table"].ToString(), dr["Column"].ToString(), dr["ReferencedTable"].ToString(), dr["ReferencedColumn"].ToString(), false,false,false);
          ListObjectProperties.Add(dr["Table"].ToString());
          ListObjectProperties.Add(dr["Column"].ToString());
          ListObjectProperties.Add(dr["ReferencedTable"].ToString());
          ListObjectProperties.Add(dr["ReferencedColumn"].ToString());
          ListObjects.Add(ListObjectProperties);
          if (SelectedList != null && SelectedList.Count > 0)
          {
            for (int i = 0; i < SelectedList.Count; i++)
            {
              if (SelectedList[i][2] == dr["ReferencedTable"].ToString())
              {
                (GrdRelationships.Rows[iRowIndex].Cells[0] as DataGridViewCheckBoxCell).Value = bool.Parse(SelectedList[i][5]);
                if (bool.Parse(SelectedList[i][5]))
                  iSelectedListCount++;

                if(bool.Parse(SelectedList[i][6]))
                  (GrdRelationships.Rows[iRowIndex].Cells[7] as DataGridViewCheckBoxCell).Value = true;
                else
                  (GrdRelationships.Rows[iRowIndex].Cells[7] as DataGridViewCheckBoxCell).Value = false;
             }
            }
          }
        }
        if (iSelectedObjectCount == GrdForeignKeys.Rows.Count)
        {
          chkObjectAll.Checked = true;
          chkListAll.Checked = false;
        }
        else if (iSelectedListCount > 0 && (iSelectedListCount == GrdRelationships.Rows.Count))
        {
          chkListAll.Checked = true;
          chkObjectAll.Checked = false;
        }
      }
      catch (SqlException sqlEx)
      {
        MessageBox.Show("OOoOOoOOoOOoOOoOOps" + " " + sqlEx.Message);
      }
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
      int iFirstGrdCount = 0;
      
      foreach (DataGridViewRow currentRow in GrdForeignKeys.Rows)
      {
        if (bool.Parse((currentRow.Cells[0] as DataGridViewCheckBoxCell).Value.ToString()))
        {
          ListObjects[currentRow.Index].Add("true");
          ListObjects[currentRow.Index].Add("false");
          ListObjects[currentRow.Index].Add(bool.Parse((currentRow.Cells[7] as DataGridViewCheckBoxCell).Value.ToString()).ToString().ToLower());
          //ListObjects[currentRow.Index].Add(bool.Parse((currentRow.Cells[8] as DataGridViewCheckBoxCell).Value.ToString()).ToString().ToLower());
        }
        else
        {
          ListObjects[currentRow.Index].Add("false");
          ListObjects[currentRow.Index].Add("false");
          ListObjects[currentRow.Index].Add(bool.Parse((currentRow.Cells[7] as DataGridViewCheckBoxCell).Value.ToString()).ToString().ToLower());
          //ListObjects[currentRow.Index].Add(bool.Parse((currentRow.Cells[8] as DataGridViewCheckBoxCell).Value.ToString()).ToString().ToLower());
        }
        iFirstGrdCount++;
      }
      foreach (DataGridViewRow currentRow in GrdRelationships.Rows)
      {
        if (bool.Parse((currentRow.Cells[0] as DataGridViewCheckBoxCell).Value.ToString()))
        {
          ListObjects[currentRow.Index + iFirstGrdCount].Add("false");
          ListObjects[currentRow.Index + iFirstGrdCount].Add("true");
          ListObjects[currentRow.Index + iFirstGrdCount].Add(bool.Parse((currentRow.Cells[7] as DataGridViewCheckBoxCell).Value.ToString()).ToString().ToLower());
          //ListObjects[currentRow.Index + iFirstGrdCount].Add("false");
        }
        else
        {
          ListObjects[currentRow.Index + iFirstGrdCount].Add("false");
          ListObjects[currentRow.Index + iFirstGrdCount].Add("false");
          ListObjects[currentRow.Index + iFirstGrdCount].Add(bool.Parse((currentRow.Cells[7] as DataGridViewCheckBoxCell).Value.ToString()).ToString().ToLower());
          //ListObjects[currentRow.Index + iFirstGrdCount].Add("false");
        }
      }
      returnForm.EmbededObjectList = ListObjects;
      this.Close();
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {
      this.Close();
    }

    private void chkObjectAll_CheckedChanged(object sender, EventArgs e)
    {
      if (!bDisableUnselect)
      {
        if (chkObjectAll.Checked)
        {
          foreach (DataGridViewRow currentRow in GrdForeignKeys.Rows)
          {
            //ListObjects
            (currentRow.Cells[0] as DataGridViewCheckBoxCell).Value = true;
            (currentRow.Cells[6] as DataGridViewCheckBoxCell).Value = false;
            //chkListAll.Checked = false;
          }
        }
        else
        {
          foreach (DataGridViewRow currentRow in GrdForeignKeys.Rows)
          {
            //ListObjects
            (currentRow.Cells[0] as DataGridViewCheckBoxCell).Value = false;
          }
        }
      }
      else
      {
        bDisableUnselect = false;
      }
    }

    private void chkListAll_CheckedChanged(object sender, EventArgs e)
    {
      if (!bDisableUnselect)
      {
        if (chkListAll.Checked)
        {
          foreach (DataGridViewRow currentRow in GrdRelationships.Rows)
          {
            //ListObjects
            (currentRow.Cells[0] as DataGridViewCheckBoxCell).Value = true;
            (currentRow.Cells[6] as DataGridViewCheckBoxCell).Value = false;
            //chkObjectAll.Checked = false;
          }
        }
        else
        {
          foreach (DataGridViewRow currentRow in GrdRelationships.Rows)
          {
            (currentRow.Cells[0] as DataGridViewCheckBoxCell).Value = false;
          }
        }
      }
      else
      {
        bDisableUnselect = false;
      }
    }

    private void GrdForeignKeys_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
      GrdForeignKeys.CommitEdit(DataGridViewDataErrorContexts.CurrentCellChange);
    }

    private void GrdForeignKeys_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
      if (e.RowIndex >= 0)
      {
        switch (e.ColumnIndex)
        {
          case 5:
            {
              if (bool.Parse((GrdForeignKeys.Rows[e.RowIndex].Cells[5] as DataGridViewCheckBoxCell).Value.ToString()) == true)
              {
                (GrdForeignKeys.Rows[e.RowIndex].Cells[6] as DataGridViewCheckBoxCell).Value = false;
                bDisableUnselect = true;
                chkListAll.Checked = false;
                bDisableUnselect = true;
                chkObjectAll.Checked = false;
              }
              break;
            }
          case 6:
            {
              if (bool.Parse((GrdForeignKeys.Rows[e.RowIndex].Cells[6] as DataGridViewCheckBoxCell).Value.ToString()) == true)
              {
                (GrdForeignKeys.Rows[e.RowIndex].Cells[5] as DataGridViewCheckBoxCell).Value = false;
                bDisableUnselect = true;
                chkListAll.Checked = false;
                bDisableUnselect = true;
                chkObjectAll.Checked = false;
              }
              break;
            }
          //case 8:
          //  {
          //    if (bool.Parse((GrdForeignKeys.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell).Value.ToString()) == false)
          //    {
          //      (GrdForeignKeys.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell).Value = true;
          //    }

          //    if (bool.Parse((GrdForeignKeys.Rows[e.RowIndex].Cells[8] as DataGridViewCheckBoxCell).Value.ToString()) == true)
          //    {
          //      foreach (DataGridViewRow row in GrdForeignKeys.Rows)
          //      {
          //        if (row.Index != e.RowIndex)
          //        {
          //          if (bool.Parse((GrdForeignKeys.Rows[row.Index].Cells[8] as DataGridViewCheckBoxCell).Value.ToString()) == true)
          //          {
          //            (GrdForeignKeys.Rows[row.Index].Cells[8] as DataGridViewCheckBoxCell).Value = false;
          //            MessageBox.Show("A object can only have one parent, You have specified more than one. Please specify only the parent object");
          //          }
          //        }
          //      }
          //    }
          //    break;
          //  }
        }
      }
    }

    private void chkObjectCommentAll_CheckedChanged(object sender, EventArgs e)
    {
      if (!bDisableUnselect)
      {
        if (chkObjectCommentAll.Checked)
        {
          foreach (DataGridViewRow currentRow in GrdForeignKeys.Rows)
          {
            //ListObjects
            (currentRow.Cells[7] as DataGridViewCheckBoxCell).Value = true;
            //chkListAll.Checked = false;
          }
        }
        else
        {
          foreach (DataGridViewRow currentRow in GrdForeignKeys.Rows)
          {
            //ListObjects
            (currentRow.Cells[7] as DataGridViewCheckBoxCell).Value = false;
          }
        }
      }
      else
      {
        bDisableUnselect = false;
      }
    }

    private void chkListCommentAll_CheckedChanged(object sender, EventArgs e)
    {
      if (!bDisableUnselect)
      {
        if (chkListCommentAll.Checked)
        {
          foreach (DataGridViewRow currentRow in GrdRelationships.Rows)
          {
            //ListObjects
            (currentRow.Cells[7] as DataGridViewCheckBoxCell).Value = true;
          }
        }
        else
        {
          foreach (DataGridViewRow currentRow in GrdRelationships.Rows)
          {
            (currentRow.Cells[7] as DataGridViewCheckBoxCell).Value = false;
          }
        }
      }
      else
      {
        bDisableUnselect = false;
      }
    }

    //private void btnAdd_Click(object sender, EventArgs e)
    //{
    //  //if (txtEOS.Text == "" && (!rbtnCDO.Checked || !rbtnCollection.Checked))
    //  //{
    //  //  MessageBox.Show("Please specify the Name of the embebed object, And whether to embed the object as a CDO or CDO Collection", "Oops", MessageBoxButtons.OK);
    //  //  return;
    //  //}
    //  //else
    //  //{
    //  //  string sEmbedString = "";
    //  //  if (rbtnCDO.Checked)
    //  //    sEmbedString = txtEOS.Text + ",Object";
    //  //  else
    //  //    sEmbedString = txtEOS.Text + ",List";

    //  //  ListObjects.Add(sEmbedString);
    //  //  //ListObjects[ListObjects.Count - 1]
    //  //  lstEOS.Items.Add(sEmbedString);
    //  //  txtEOS.Text = "";
    //  }
    //}

    //private void btnRemove_Click(object sender, EventArgs e)
    //{
    //  for (int iDX = 0; iDX < lstEOS.Items.Count; iDX++)
    //  {
    //    if (lstEOS.Items[iDX].Selected)
    //    {
    //      ListObjects.Remove(lstEOS.Items[iDX].Text);
    //      lstEOS.Items[iDX].Remove();
    //    }
    //  }
    //}
  }
}